import {assert} from "../../utils/assert";
import {stringUtils} from "../../utils/stringUtils";
import {MidwareConfig, CustomPlayerConfig} from "../midware";
import {requestParams} from "../../utils/request";
import jQuery from 'jquery';
import {supportFunction} from "../../utils/supportFunction";

const DEFAULT_LANGUAGE_CODE = "zh_CN";
let i18nInit = false;

class I18nManager {
    constructor() {
        if (!I18nManager.instance) {
            this._languageConfig = {};
            this._languageSet = {};

            I18nManager.instance = this;
        }

        return I18nManager.instance;
    }

    get CurrentLanguage() {
        return requestParams.params["_lang_"] === undefined ? DEFAULT_LANGUAGE_CODE : requestParams.params["_lang_"];
    }

    loadConfig(path = undefined, file = 'language.json', async = true) {
        if (i18nInit) {
            console.warn("Internationalization Resource Manager did not initialization");
            return;
        }
        const cPath = stringUtils.urlJoin(MidwareConfig.BasePath, path, file, '?releaseNum=' + MidwareConfig.PlayerReleaseNumber);
        return jQuery.ajax({
            url: cPath,
            dataType: 'json',
            async: async
        }).done(data => {
            if (Array.prototype.isArray(data) && data.length > 0) {
                const presenterConfig = data.filter(function (item) {
                    return item.type === "presenter";
                });
                //将配置转换为较容易识别的模式
                presenterConfig.each((item) => {
                    if (!this._languageConfig[item.name]) {
                        //初始化配置集合
                        this._languageConfig[item.name] = {};
                        //初始化语言集合
                        this._languageSet[item.name] = {};
                        //初始化每个语言的集合
                        item.urls.each((lang) => {
                            this._languageConfig[item.name][lang.code] = lang.url;
                        });
                    }
                });
            }
            //标记加载完成
            i18nInit = true;
            Object.freeze(this);
        }).fail(() => {
            console.warn('language config file not loaded!');
        });
    }

    /**
     * 获取模块的国际化资源对象
     * @param key 资源键值
     * @param lang 语言编码
     * @param async 同步读取语言资源
     * @returns {JQueryPromise<T>}
     */
    loadLanguage(key, lang, async = true) {
        if (lang === undefined) {
            lang = DEFAULT_LANGUAGE_CODE;
        }
        assert(i18nInit === false, "language config not load");
        let deferred = jQuery.Deferred();
        if (!this._languageSet[key]) {
            //如果配置中不存在指定语言配置就直接返回
            deferred.resolve({lang: undefined});
        } else {
            if (this._languageSet[key][lang]) {
                //配置中存在且加载过
                deferred.resolve({lang: this._languageSet[key][lang]});
            } else {
                //配置中存在但没有加载
                const langUrl = stringUtils.urlJoin(MidwareConfig.BasePath, MidwareConfig.LanguageBasePath,
                    this._languageConfig[key][lang], '?releaseNum=' + MidwareConfig.PlayerReleaseNumber);
                jQuery.ajax({
                    url: langUrl,
                    async: async,
                    dataType: 'json'
                }).done(langData => {
                    //需要经过版本检查
                    this._languageSet[key][lang] = this._versionCheck(key, langData);
                    deferred.resolve({lang: this._languageSet[key][lang]});
                }).fail(() => {
                    deferred.resolve({lang: undefined});
                });
            }
        }
        return deferred.promise();
    }

    /**
     * 替换指定View对象的语言文本
     * @param view View对象
     * @param langSet 语言对象
     */
    replaceView(view, langSet) {
        if (langSet === undefined || langSet === null) {
            return;
        }
        assert(i18nInit === false, "language config not load");
        let $view = !(view instanceof jQuery) ? $(view) : view;
        jQuery.each(langSet, (key, value) => {
            let items = $view.find('.lang_' + key);
            if (items.length > 0) {
                items.text(value);
            }
        });
    }

    //提取
    _versionCheck(key, langSet) {
        const mVer = this._getVersionValue(CustomPlayerConfig.Presenters[key].version);
        const versionRes = {};

        for (let key in langSet) {
            if (key.indexOf('@') > 0) {
                let temp = key.split('@');
                if (versionRes[temp[0]] === undefined) {
                    versionRes[temp[0]] = [];
                    versionRes[temp[0]].push({
                        key: 0,
                        value: langSet[temp[0]]
                    });
                }
                const verValue = this._getVersionValue(temp[1]);
                for (let i = 0, len = versionRes[temp[0]].length; i < len; i++) {
                    if (verValue < versionRes[temp[0]][i].key) {
                        versionRes[temp[0]].insertOf(i, {key: verValue, value: langSet[key]});
                        break;
                    }
                    if (i === len - 1) {
                        versionRes[temp[0]].push({key: verValue, value: langSet[key]});
                    }
                }
                //移除所有带版本的Key
                delete langSet[key];
            }
        }

        if (supportFunction.isEmptyObject(versionRes)) {
            return langSet;
        }
        //确认所有有版本的Key最终应该使用那个
        for (let key in versionRes) {
            const tempArray = versionRes[key];
            for (let i = 0; i < tempArray.length; i++) {
                if(tempArray[i].key === mVer) {
                    //能够找到对应版本, 直接使用
                    langSet[key] = tempArray[i].value;
                    break;
                }
                if(tempArray[i].key > mVer && i !== 0) {
                    //能够找到比当前版本大的版本, 使用前一个版本的值
                    langSet[key] = tempArray[i - 1].value;
                    break;
                }
                //当前版本比所有配置版本都大, 使用最后一个版本的值
                langSet[key] = tempArray[i].value;
            }
        }
        return langSet;
    }
    //获取版本的分值,按照3位版本, 每个版本2位数计算
    _getVersionValue(version) {
        const temp = version.split('.');
        if (temp.length !== 3) {
            return -1;
        }
        return (temp[0] * 10000) + (temp[1] * 100) + (temp[2] * 1);
    }
}

const i18nManager = new I18nManager();
export default i18nManager;